import {
  AvailableTaskInfo,
  restoreAvaliableKey,
  useGigaNotPersisStore,
} from '@/store/gigaNotPersist';
import { getAvaliableDB, DB as gigaAvaliableDB } from '@/lib/gigaAvaliable';
import { confirmMessage } from '@/lib/imperative';
import { toast } from 'sonner';

type Props = {
  children?: React.ReactNode;
  className?: string;
  runTask: (skuInfo: string, timeStamp: number, db: gigaAvaliableDB) => Promise<void>;
  container?: string;
};

export default function AvaliableResume({
  children,
  className,
  runTask,
  container,
  ...props
}: Props) {
  const resumeAvaliableTasks = JSON.parse(
    localStorage.getItem(restoreAvaliableKey) || '[]',
  ) as AvailableTaskInfo[];
  const dispatch = useGigaNotPersisStore((state) => state.dispatch);
  useEffect(() => {
    async function resumeTask() {
      if (resumeAvaliableTasks.length > 0) {
        const tasks = [...resumeAvaliableTasks];
        localStorage.setItem(restoreAvaliableKey, '[]');
        resumeAvaliableTasks.length = 0;
        // console.log(resumeAvaliableTasks);
        const isResumeTask = await confirmMessage({
          title: '采集任务恢复',
          description: `检测到上次采集还有 ${tasks.length} 个任务未完成，是否继续采集？`,
          confirmText: '继续采集',
          cancelText: '不采集',
          container: container,
        });
        if (isResumeTask) {
          const categoryName = tasks[0].categoryName;
          const timeStamp = Date.now();
          dispatch({
            type: 'update',
            update(draftState) {
              draftState.availableConcurrent.currentCategoryName = categoryName;
            },
          });
          const skuInfos = tasks.map((task) => {
            return task.skuIdInfo;
          });
          const db = await getAvaliableDB(categoryName);
          await Promise.all(
            skuInfos.map((skuInfo) => {
              return new Promise((resolve, reject) => {
                dispatch({
                  type: 'enqueueTask',
                  resolve,
                  reject,
                  task: {
                    handleTask: async () => {
                      await runTask(skuInfo, timeStamp, db);
                    },
                    taskInfo: {
                      id: skuInfo,
                      skuIdInfo: skuInfo,
                      categoryName: categoryName,
                    },
                  },
                });
              });
            }),
          );
          toast.success(`完成 ${categoryName} 分类下的所有的产品获取操作`);
        }
      }
    }
    resumeTask();
  }, []);
  return (
    <div className={className} {...props}>
      {/* AvaliableResume */}
    </div>
  );
}
